/**
 * Created by Administrator on 2017/4/11.
 * @description 通用http请求封装
 * @testId 374968
 */
import qs from 'qs';
import Utils from 'utils/utils';
import ApiConfig from './config';
import modal from 'utils/modal';
import loading from 'utils/loading';
import jsbridge from 'utils/jsbridge';
import loginFilter from 'filters/loginFilter';
import HttpCode from 'api/httpCode';
import storage from 'utils/storage';

/**根域名*/
let baseUrl = null;

let stream = weex.requireModule('stream');

//定义公共请求头变量
let headerParams = null;

//获取基本api信息列表
const apiList = ApiConfig.apiList;

//定义超时时间_单位ms_默认20s
const timeOut = 20000;

/**
 * 获取公共请求头参数
 */
+function(){
    if(!headerParams){
        jsbridge.getAppConfig(res => {
            headerParams = res || {};
            //增加utf-8的编码格式
            headerParams['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
        });
    }
}();


/**
 * @description 响应返回信息处理
 * @param res
 * @param resolve
 * @param reject
 * @param hideLoading
 */
function response(res, resolve, reject, hideLoading) {

    hideLoading && loading.hideLoading();//关闭加载进度条

    let _ok = res.ok; //返回状态
    let code = res.status; //状态码
    let txt = '错误信息: ' + res.statusText;//txt描述信息

    if(code == -1){ //请求失败
        reject({code: -1, msg: '连接错误!'});
    } else {
        if(_ok && res.data) {
            if(res.data.code == 0){
                console.log('返回数据：' + JSON.stringify(res.data));
                resolve(res.data);
            } else {
                reject(res.data);
            }
        } else {
            let key = 'HTTP_' + code;
            let ret = {
                code: code,
                msg: txt
            };
            if(typeof HttpCode[key] != 'undefined') {
                ret = HttpCode[key];
            }
            reject(ret);
        }
    }
}

/**
 * @description 动态获取api
 * @param key
 * @param params
 */
function getConfig(key, params) {
    let _api = apiList[key] || {};
    params = params || {};
    if(!_api.url || _api.url == undefined || _api.url == null) {
        modal.toast('接口[' + key + '] context url 未配置');
        return null;
    }
    if(_api.action && _api.action != '') params.action = _api.action;
    return {
        type: (_api.type && _api.type !='') ? _api.type : 'GET',
        url: _api.url,
        author: _api.author || false,
        params: params
    };
}

/**
 * @method get请求
 * @param url 请求的context url封装在了api.config.js中了
 * @param params 请求参数
 * @param hideLoading 是否显示隐藏进度条
 */
function get(url, params, hideLoading) {
    return new Promise((resolve, reject) => {
        //请求用户userregion收货地址信息
        storage.getItem('region').then(res=>{
            params.userregion = res || null;
            console.log('请求公共参数：' + JSON.stringify(headerParams));
            console.log('请求业务参数：' + JSON.stringify(params));
            hideLoading && loading.showLoading(); //打开加载进度条
            try {
                stream.fetch({
                    method: 'GET',
                    url: `${baseUrl + url}?${qs.stringify(params)}`,
                    type: 'json',
                    timeout: params.timeout || timeOut,
                    headers: headerParams
                }, res => {
                    response(res, resolve, reject, hideLoading);
                }, progress => {
                    console.log('['+ baseUrl + url +']报文长度:' + progress.length);
                });
            } catch (e){
                hideLoading && loading.hideLoading();//关闭加载进度条
                console.log('[GET]异常错误:' + e);
                reject({
                    code: -3003,
                    msg: '异常错误:' + e
                });
            }
        });
    });
}

/**
 * @method post请求
 * @param url 请求url 封装在api.config.js中
 * @param body 请求的主体
 * @param hideLoading 是否显示隐藏进度条
 */
function post(url, body, hideLoading) {
    return new Promise((resolve, reject) => {
        //请求用户userregion收货地址信息
        storage.getItem('region').then(res=>{
            body.userregion = res || null;
            console.log('请求公共参数：' + JSON.stringify(headerParams));
            console.log('请求业务参数：' + JSON.stringify(body));
            hideLoading && loading.showLoading(); //打开加载进度条
            try {
                stream.fetch({
                    method: 'POST',
                    url: `${baseUrl + url}`,
                    type: 'json',
                    timeout: body.timeout || timeOut,
                    headers: headerParams,
                    body: qs.stringify(body)
                }, res => {
                    response(res, resolve, reject, hideLoading);
                }, progress => {
                    console.log('['+ baseUrl + url +']报文长度:' + progress.length);
                });
            } catch (e){
                hideLoading && loading.hideLoading();//关闭加载进度条
                console.log('[GET]异常错误:' + e);
                reject({
                    code: -3003,
                    msg: '异常错误:' + e
                });
            }
        });
    });
}

/**
 * 发送http请求
 * @param api key
 * @param params
 * @param hideLoading 是否隐藏进度条 默认为true 显示进度条
 * @returns {Promise}
 */
exports.sendHttp = function (api, params, hideLoading) {

    if(hideLoading === undefined) hideLoading = true;

    return new Promise((resolve, reject) => {
        if(typeof api == 'undefined' || api=='' || !api) {
            reject('api name is null');
        }
        let config = getConfig(api, params);
        loginFilter.isLogin(config.author).then(user => {
            let _user = user;
            jsbridge.getEnv(res => {
                if(!res) baseUrl = ApiConfig.testServer;
                else baseUrl = ApiConfig.prodServer;

                //用户hash值
                config.params.hash = _user || null;

                if(config.type && config.type.toUpperCase() === 'POST') {
                    post(config.url, config.params, hideLoading).then(resolve, reject);
                } else get(config.url, config.params, hideLoading).then(resolve, reject);
            });
        }, () =>{
            console.log('登录异常');
        });
    });
};